import pymysql
import threading
lock = threading.Lock()



class DB:
    def __init__(self) -> None:
        self.conn = pymysql.connect(host='localhost',port=3306,user='root',password='mysql',db='userstest',cursorclass=pymysql.cursors.DictCursor)
        self.cursor = self.conn.cursor()

    def reConnect(self):
        try:
                self.conn.ping()
        except:
                self.conn = pymysql.connect(host='localhost',port=3306,user='root',password='mysql',db='userstest',cursorclass=pymysql.cursors.DictCursor)
                self.cursor = self.conn.cursor()

    #更新添加
    def update(self,sql):
            self.cursor.execute(sql)
        #     self.conn.commit()
        #     return self.cursor.lastrowid

    #获取一条
    def findOne(self,sql):
            self.reConnect()
          
            self.cursor.execute(sql)
            res = self.cursor.fetchone()
          
            return res
    #获取多条
    def findAll(self,sql):
            self.reConnect()
            lock.acquire()
            self.cursor.execute(sql)
            res = self.cursor.fetchall()
            lock.release()
            return res

    #提交方法
    def commit(self):
            self.conn.commit()
    #回滚方法
    def rollback(self):
            self.conn.rollback()

db = DB()